<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="型号组合id" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入型号组合id"
          clearable
        />
      </el-form-item>
      <el-form-item label="型号组合名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入型号组合名称"
          clearable
        />
      </el-form-item>
      <el-form-item label="主设备" prop="primaryId">
        <el-select v-model="queryParams.primaryId" filterable placeholder="请选择主设备">
          <el-option
            v-for="item in main_device_model"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="子设备" prop="subIds">
        <el-select v-model="queryParams.subIds" filterable placeholder="请选择子设备">
          <el-option
            v-for="item in sub_device_model"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['produce:produce-plan:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['produce:produce-plan:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['produce:produce-plan:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getComposeDeviceModelList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="composeDeviceModelList" @selection-change="handleSelectionChange"  :default-sort = "{prop: 'date', order: 'descending'}">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column sortable label="id" align="center" prop="id" />
      <el-table-column label="型号组合名称" align="center" prop="name" />
      <el-table-column label="主设备型号" align="center" prop="primaryDeviceName"/>
      <el-table-column label="子设备型号" align="center" prop="subDeviceNames">
        <template slot-scope="scope">
          <div v-if="scope.row.subDeviceNames && scope.row.subDeviceNames.length > 0">
            <div v-for="item in scope.row.subDeviceNames" :key="item">
              {{ item }}
            </div>
          </div>   
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getComposeDeviceModelList"
    />

    <!-- 添加或修改设备型号组合对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-col :span="24">
          <el-form-item label="型号组合名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入型号组合名称"  maxlength="30" show-word-limit/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="主设备型号" prop="primaryId">
            <el-select v-model="form.primaryId" filterable placeholder="请选择主设备">
              <el-option
                v-for="item in main_device_model"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="子设备型号" prop="subIds">
            <el-select v-model="form.subIds" filterable multiple placeholder="请选择子设备">
              <el-option
                v-for="item in sub_device_model"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" placeholder="请输入备注"   maxlength="50" show-word-limit/>
          </el-form-item>
        </el-col>
      </el-form>  


      

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>

    </el-dialog>
  </div>
</template>

<script>

import { listDeviceModelCompose, getDeviceModelComposeDetail, addDeviceModelCompose, updateDeviceModelCompose, exportDeviceModelCompose, delDeviceModelCompose } from "@/api/device/deviceModelCompose";
import { listDeviceModel } from "@/api/device/deviceModel";

export default {
  name: "project",
  data() {
    return {
      // 表单数据
      form : {
        address: null,
        classify:null,
        code: null,
        direction: null,
        model: null,
        name: null,
        paimianAngle: null,
        port: null,
        type: 1
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 主设备型号
      main_device_model: [],
      // 子设备型号
      sub_device_model: [],
      // 型号组合
      composeDeviceModelList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 型号组合
      queryParams:{
        pageNum: 1,
        pageSize: 10,
        name:'',
        primaryId:'',
        subId:'',
        subIds:'',
        orderByColumn:'id',
        isAsc:'desc'
      },
      // 型号查询参数
      modelQueryParams: {
        pageNum: 1,
        pageSize: 1000,
        model: null,
        code: null,
        name: null,
        remark: null,
        type:1,
        orderByColumn:'id',
        isAsc:'desc'
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "型号组合名称不能为空", trigger: "blur" }
        ],
        primaryId: [
          { required: true, message: "设备型号不能为空", trigger: "blur" }
        ],
        subIds: [
          { required: true, message: "主设备型号编号不能为空", trigger: "blur" }
        ],

      }
    };
  },
  created() {
    this.getMainDeviceModelList();
    this.getSubDeviceModelList();
    this.getComposeDeviceModelList();
  },
  methods: {
    /** 获取设备型号组合列表 */
    getComposeDeviceModelList(){
      this.loading = true;
      listDeviceModelCompose(this.queryParams).then((res) =>{
        if(res.code === 200){
          if(res.rows){
            for(var i=0;i<res.rows.length;i++){
              var strArr = res.rows[i].subId.split(',')
              var intArr = []
              intArr = strArr.map(item =>{
                return +item
              })
              res.rows[i].subIds = intArr
              res.rows[i].primaryId = parseInt(res.rows[i].primaryId)
            }
          }
          this.composeDeviceModelList = res.rows
        }
      }).catch((err) =>{
        this.$message.error("设备型号组合列表获取失败，原因："+err.message)
      }).finally(() =>{
        this.loading = false;
      })
    },
    /** 获取主设备型号列表 */
    getMainDeviceModelList(){
      this.modelQueryParams.type = 1
      listDeviceModel(this.modelQueryParams).then((res) =>{
        if(res.code === 200){
          if(res.rows){
            for(var i=0;i<res.rows.length;i++){
              let temp = {
                label:res.rows[i].name,
                value:res.rows[i].id
              }
              this.main_device_model.push(temp)
            }
          }
        }
      }).catch((err) =>{
        this.$message.error("主设备型号列表获取失败，原因："+err.message)
      }).finally(() =>{
      })
    },
    /** 获取子设备型号列表 */
    getSubDeviceModelList(){
      this.modelQueryParams.type = 2
      listDeviceModel(this.modelQueryParams).then((res) =>{
        if(res.code === 200){
          if(res.rows){
            for(var i=0;i<res.rows.length;i++){
              let temp = {
                label:res.rows[i].name,
                value:res.rows[i].id
              }
              this.sub_device_model.push(temp)
            }
          }
        }
      }).catch((err) =>{
        this.$message.error("子设备型号列表获取失败，原因："+err.message)
      }).finally(() =>{
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        address: null,
        classify:null,
        code: null,
        direction: null,
        model: null,
        name: null,
        paimianAngle: null,
        port: null,
        type: 1
      }
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getComposeDeviceModelList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加主设备型号";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDeviceModelComposeDetail(id).then(res => {
        if(res.data){
            var strArr = res.data.subId.split(',')
            var intArr = []
            intArr = strArr.map(item =>{
              return +item
            })
            res.data.subIds = intArr
            res.data.primaryId = parseInt(res.data.primaryId)
        }
        this.form = res.data;
        this.open = true;
        this.title = "修改主设备型号信息";
      });
    },
    /** 提交按钮 */
    submitForm(){
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            if(this.form.subIds){
              this.form.subId = this.form.subIds.join(',')
            }
            updateDeviceModelCompose(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getComposeDeviceModelList();
            });
          } else {
            if(this.form.subIds){
              this.form.subId = this.form.subIds.join(',')
            }
            addDeviceModelCompose(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getComposeDeviceModelList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除型号组合id为"' + ids + '"的数据项？').then(function() {
          // 修改为逻辑删除
        return delDeviceModelCompose(ids);
      }).then(() => {
        this.getComposeDeviceModelList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('/genius/platform-device-compose/export', {
        ...this.queryParams
      }, `型号组合列表_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style lang="scss">
.formTitle{
  width:100%;
  text-align:center;
  margin:15px 0 15px 0;
  font-weight:border;
  font-size:20px
}
</style>
